package com.aaa.sso.service;

import com.aaa.common.bo.User;
import com.aaa.common.constant.ExceptionConstant;
import com.aaa.common.constant.ReturnCode;
import com.aaa.common.util.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService{
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Result userLogin(String userName, String password) {
        //收集用户信息
        UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(userName,password);
        //获取主体对象
        Subject currentUser= SecurityUtils.getSubject();

        //System.out.println("usernamePasswordToken---"+usernamePasswordToken);
       //System.out.println("currentUser---"+currentUser);
        try {
            //登录，执行认证过程
            currentUser.login(usernamePasswordToken);
            //认证成功后返回用户信息
            User user = (User) currentUser.getPrincipal();

            //将登录的用户信息存储到session用户权限

            Session session=currentUser.getSession();
            session.setAttribute("user",user);
            User user1= (User) session.getAttribute("user");
            Integer userId= user1.getUserId();

            //生成token(令牌)
            String token= userName+System.currentTimeMillis();
            System.out.println(user+"--------"+token);
            //放入redis
            redisTemplate.opsForValue().set(token,user,30, TimeUnit.MINUTES);
            return new Result(ReturnCode.SUCCESSS.getCode(),
                        ReturnCode.SUCCESSS.getMsg(),token,userId);
        }catch (AuthenticationException e) {
            e.printStackTrace();
        }
        return new Result(ExceptionConstant.EORRO_USERNAME_OR_PASSWORD.getErrorCode(),
                ExceptionConstant.EORRO_USERNAME_OR_PASSWORD.getErrorMessage(),null);
    }

    /**
     * 校验token
     * @param token
     * @return
     */
    @Override
    public boolean checkToken(String token) {
        return redisTemplate.hasKey(token);
  }
    /**
     * 退出删除token
     * @return
     */
    @Override
    public int loginout() {
        //获取主体对象
        Subject currentUser = SecurityUtils.getSubject();
        currentUser.logout();
        return 0;
    }
}
